#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re

import pymongo

from config import *

client = pymongo.MongoClient(MONGO_URI)
db = client["xueqiu"]
# from xueqiu.updateCookies import updateCookies
from selenium import webdriver;
from selenium.webdriver.support.ui import WebDriverWait
import json
import requests

# 订单成功
# 支付成功
# 会员提取码：2018051154016
# 成功金额：5
cookies = {}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
}


def get_proxy_ip():
    try:
        res = requests.get("http://127.0.0.1:5000/get")
        if res.status_code == 200:
            proxy = res.text
            return proxy
        else:
            get_proxy_ip()
    except Exception as e:
        print(e)
        get_proxy_ip()


def update(id=252852):
    print("update cookies",id)
    # 设置代理
    try:
        global cookies
        browser = webdriver.Chrome()
        # browser.set_window_size(1400,900)
        wait = WebDriverWait(browser, 10)
        browser.get("https://xueqiu.com/P/ZH1329019")
        # cube - content
        # user_name = wait.until(
        #     EC.presence_of_element_located((By.CSS_SELECTOR, "cube-content"))
        # )
        results = browser.get_cookies()
        for res in results:
            cookies[res.get("name")] = res.get("value")
        browser.quit()
        start_cueb(id)
    except Exception as  e:
        print(e)
        update()


def saveToMongo(result):
    try:
        if db["cube_info"].insert(result):
            print("save result success")
    except:
        print("save mongo error")


def get_data():
    queryArgs = {}
    projectionFields = {'_id': False}  # 用字典指定
    result = db["cube_info20180510"].find(queryArgs, projectionFields)
    return result


def updateToMongo(cube_stocks, cube_socre):
    try:
        db["cube_info20180510"].update({"cube_socre": cube_socre}, {"$set": {"cube_stocks": cube_stocks}})
        print("update success")
    except Exception as e:
        print(e)
        print("update error")


def get_cube_id(obj):
    obj = json.loads(obj)
    result = None
    if "symbol" in obj:
        result = obj.get("symbol", None)
    # print(result)
    return result











    # updateCookies.update()


def get_cube_index(id):
    print(id)

    try:
        url = "https://xueqiu.com/P/{id}".format(id=id)
        res = requests.get(url, headers=headers, cookies=cookies)
        if res.status_code == 200:
            pass

    except Exception as e:
        print(e)
        return None


def start_cueb(id=100000):
    print(id)
    for i in range(id, 1000000):
        id = "ZH" + str(i)
        get_cube_rank(id)


def parse_cube_detail(html):
    result = re.compile("SNB.cubeInfo = (.*)").search(html)
    if result:
        # print(result.group(1))
        return result.group(1)
    else:
        return None


def get_cube_score(id):
    url = "https://xueqiu.com/cubes/rank/summary.json?symbol={cube_id}&ua=web".format(cube_id=id)
    res = requests.get(url, headers=headers, cookies=cookies)
    if res.status_code == 200:
        return res.text
    else:
        return None


def get_cubeinfo(id, cube_sore):
    print(id, cube_sore)
    if id == None or cube_sore == None:
        return
    cube_stocks = get_cube_index(id)
    # cube_score=get_cube_score(id)
    cube = {
        "cube_stocks": cube_stocks,
        "cube_socre": cube_sore
    }
    print(cube)
    if cube_stocks == None:
        return
    # saveToMongo(cube)
    updateToMongo(cube_stocks, cube_sore)


def get_cube_rank(id):
    print(id)
    url = "https://xueqiu.com/cubes/rank/summary.json?symbol={cube_id}&ua=web".format(cube_id=id)
    try:
        res = requests.get(url, headers=headers, cookies=cookies)
        if res.status_code == 200:
            result = res.text
            if result != None:
                ranks = json.loads(result)
                if "total_score" in ranks:
                    score = ranks.get("total_score")
                    sub_score = ranks.get("sub_scores")
                    absGain = sub_score[0].get("score")  # 盈利能力
                    maxDrawDown = sub_score[1].get("score")  # 最大回撤
                    volatility = sub_score[2].get("score")  # 盈利方差
                    dispersion = sub_score[3].get("score")  # 持股分散性
                    replication = sub_score[4].get("score")  # 可复制性 换手率和流动性
                    if score > 50 and absGain > 13 and maxDrawDown > 9 and volatility > 10 and dispersion>10:
                        cube = {
                            "cube_id": id,
                            "sub_score": score,
                            "absGain": absGain,
                            "maxDrawDown":maxDrawDown,
                            "volatility": volatility,
                            "dispersion": dispersion,
                            "replication": replication
                        }
                        print(cube)
                        saveToMongo(cube)
        else:
            print(res.status_code)
            update(int(id[2:]))
    except Exception as e:
        print(e)
        update(int(id[2:]))
